﻿using ArticleandSiteData;
using HtmlAgilityPack;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Provider;
using Windows.UI;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Web.Http;
using Windows.Web.Http.Headers;

namespace SplitViewOptions
{
   public class HtmlUsedFunction
    {
        public async static Task upload(Stream stream1,string uploadname,string title)
        {
            string requesturl = "https://api.bmob.cn/2/files/" + uploadname;
           
         
            Uri uri = new Uri(requesturl);
            // const int contentLength = 1000;
            //  Stream stream2 = GenerateSampleStream(contentLength);
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            httpClient.DefaultRequestHeaders.Add("X-Bmob-REST-API-Key", App.Restkeyid);
            httpClient.DefaultRequestHeaders.Add("X-Bmob-Application-Id", App.Applicationid);
           
            HttpStreamContent streamContent = new HttpStreamContent(stream1.AsInputStream());
            streamContent.Headers.ContentType = new HttpMediaTypeHeaderValue("image/jpeg");
            Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri);
            request.Content = streamContent;

            // Do an asynchronous POST.
            Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request);


            if (response.StatusCode == Windows.Web.Http.HttpStatusCode.Ok)
            {
                
                string content = response.Content.ToString();
                upobject resualist = (upobject)JsonConvert.DeserializeObject(content, typeof(upobject));
                sharepic(resualist.url, resualist.filename,title);
                await App.showmessage("上传成功");

                //  MessageDialog one = new MessageDialog("注册成功,请登录");
                //await  one.ShowAsync();
                // registerbrn.IsEnabled = true;
            }
            else
            {
               
                await App.showmessage("上传失败");

                // MessageDialog one = new MessageDialog("注册失败");
                //await one.ShowAsync();
                // registerbrn.IsEnabled = true;
            }
        }
        private static async void sharepic(string url, string name,string title)
        {
          
            string api = "https://api.bmob.cn/1/classes/sharepictable";
            Dictionary<string, string> userdic = new Dictionary<string, string>();
            userdic.Add("picurl", url);

            userdic.Add("weburl", App.Currenturl.AbsoluteUri);

            userdic.Add("pictitle", title);

            userdic.Add("pictags", title);

            //userdic.Add("mainwebspace", mainwebspacebox.Text);
            //userdic.Add("likesbox", likesbox.Text);
            //userdic.Add("introducebox", introducebox.Text);

            string jsonstrdic = RequestHelper.DictionaryTojsonstr(userdic);
            var responce = await BmobWebsiteData.AddoneWebsite<object>(api, jsonstrdic);
            if (responce.StatusCode == System.Net.HttpStatusCode.Created)
            {
              
                await App.showmessage("分享成功");
            }
            else
            {
               
                await App.showmessage("分享失败");
             
            }
        }
        public static async Task<List<string>> getallimage(string url)
        {
            List<string> urllist = new List<string>();
            List<string> buildinurllist;
            var document = await new HtmlWeb().LoadFromWebAsync(url);
            var urls = document.DocumentNode.Descendants("img");
            foreach (var a in urls)
            {
                if (a.HasAttributes && a.Attributes["src"] != null)
                {
                    string str = a.Attributes["src"].Value;
                    if (str.StartsWith("http"))
                    {
                        urllist.Add(str);
                    }
                    else
                    {
                        urllist.Add(generateabsoluteurl(str));
                    }
                }
                else
                {

                }
            }
            return urllist;
        }
        public static async Task<List<string>> getallimageByhtmlstring(string htmlstring)
        {
            List<string> urllist = new List<string>();
            var document = new HtmlDocument();
            TextReader txtreader = new StringReader(htmlstring);
            document.Load(txtreader);
            var urls = document.DocumentNode.Descendants("img");
            Debug.WriteLine(urls.Count());
            foreach (var a in urls)
            {
                if (a.HasAttributes && a.Attributes["src"] != null)
                {
                    string str = a.Attributes["src"].Value;
                    if (str.StartsWith("http"))
                    {
                        urllist.Add(str);
                    }
                    else
                    {
                        if(!string.IsNullOrEmpty(str))
                        urllist.Add(generateabsoluteurl(str));
                    }
                }
                else
                {

                }
            }
            return urllist;
        }
        public static bool containsdomainname(string domanname)
        {
              foreach(var a in array)
            {
                if (domanname.Contains(a))
                {
                    return true;
                }
                   
            }
           return false;
        }
     static   string[] array = new string[] {"qq", "baidu", "taobao", "163", "ifeng", "jd.com", "sohu", "sina.com", "google.com","bing.com","tianya.com","meituan.com","xinhua.com","people.com","xinhua.net","cctv.com","360.com","sogou.com","soso.com","hao123.com","youku.com","letv.com","tmall.com","iqiyi.com","eastmoney.com","58.com","ganji.com",
                      "tuniu.com","suning.com","zhilian.com","51job.com","qidian.com","jiayuan.com","ithome.com","hexun.com","bilibili.com","10jqka.com","nipic.com","visualchina.com","msdn.com","amazon.com","126.com","tudou.com","duitang.com","zcool.com","weibo.com","weixin.com",
                            "renren.com","kaixin.com","youtube.com","facebook.com","twitter.com","peolple.cn","google","yahoo.com","wikipedia.org","live.com","hotmail","email","ebay","bing.com","vk.com","msn.com","instagram","yandex.ru",
               "zhihu","amazon","blogspot.com","ask.com","pinterest.com","wordpress.com","tmall.com","reddit.com","mail","readcolor.com","imgur.com","microsoft.com","windows",
                                 };
        private static string generateabsoluteurl(string str)
        {
            Debug.WriteLine(App.Currenturl.Host + "app current host");
            Debug.WriteLine("http://" + App.Currenturl.Host + str + "app current host");
            if(str.StartsWith("/"))
            {
                return "http://" + App.Currenturl.Host + str;
            }
            else
            {
                return "http://" + App.Currenturl.Host +"/"+str;
            }
        }
        //private static List<string> allbuildinurl()
        //{
           
        //    List<string> allbuildinurl = new List<string>();
        //    allbuildinurl.AddRange(array);
        //    Debug.WriteLine(array.Length + "arrayel");
        //    return allbuildinurl;
        //}
        //public static string StringToJsonStr(string url)
        //{
        //}
        public static string  GetShareStringTyep(string url)
        {
            string typeresult = string.Empty;
            if (url.StartsWith("http")|| url.StartsWith("www"))
            {
                if(url.Contains("html")|| url.Contains(".htm"))
                {
                    typeresult = "article";
                }
                else
                {
                    typeresult = "site";
                }
            }
            else
            {
                typeresult = "text";
            }
            return typeresult;
        }
        public static async Task<string> gethtmlstring(string url)
        {
            Debug.WriteLine(url);
            string resultstr = string.Empty;
            WebResponse webResponse = null;
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "GET";
            string responseStr = null;
         // webRequest.Timeout = 50000;
           //webRequest.ContentType = "text/html";
            Encoding responceencoding = null;
            try
            {
                //尝试获得要请求的URL的返回消息
                webResponse = await webRequest.GetResponseAsync();
                string str = webResponse.ContentType;
                if(str.Contains("charset")&&str.Contains("=")&&str.Contains("text/html"))
                {
                    string[] splitresult = str.Split('=');
                    if(splitresult.Length>1)
                    {
                        string encodingstr = splitresult[1];
                        if(encodingstr.ToLower()=="utf-8")
                        {
                            responceencoding = Encoding.UTF8;
                        }
                       else if (encodingstr.ToLower() == "gbk"|| encodingstr.ToLower() == "gb2312")
                        {
                            responceencoding = CodePagesEncodingProvider.Instance.GetEncoding(936);
                        }
                        else
                        {
                            responceencoding = Encoding.UTF8;
                        }
                    }

                }
                else
                {
                    responceencoding = Encoding.UTF8;
                }
            }
            catch (WebException e)
            {
                //发生网络错误时,获取错误响应信息
                responseStr = "发生网络错误！请稍后再试";
            }
            catch (Exception e)
            {
                //发生异常时把错误信息当作错误信息返回
                responseStr = "发生错误：" + e.Message;

            }
            finally
            {
                if (webResponse != null)
                {
                    //获得网络响应流                  
                   if(responceencoding==null)
                    {
                        responceencoding = Encoding.UTF8;
                    }
                    using (StreamReader responseReader = new StreamReader(webResponse.GetResponseStream(), responceencoding))
                    {
                       
                        responseStr = responseReader.ReadToEnd();//获得返回流中的内容
                        Debug.WriteLine(responseStr);
                    }
                    webResponse.Dispose();
                  //  webResponse.Close();//关闭web响应流
                }
            }
            return responseStr;
         
        }
        //public static async Task<FileUpdateStatus> SaveToPngImage(WriteableBitmap bitmap, PickerLocationId location, string fileName)
        //{
        //    var savePicker = new FileSavePicker
        //    {
        //        SuggestedStartLocation = location
        //    };
        //    savePicker.FileTypeChoices.Add("Png Image", new[] { ".png" });
        //    savePicker.SuggestedFileName = fileName;
        //    StorageFile sFile = await savePicker.PickSaveFileAsync();
        //    if (sFile != null)
        //    {
        //        CachedFileManager.DeferUpdates(sFile);


        //        using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
        //        {
        //            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
        //            Stream pixelStream = bitmap.PixelBuffer.AsStream();
        //            byte[] pixels = new byte[pixelStream.Length];
        //            await pixelStream.ReadAsync(pixels, 0, pixels.Length);
        //            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
        //                      (uint)bitmap.PixelWidth,
        //                      (uint)bitmap.PixelHeight,
        //                      96.0,
        //                      96.0,
        //                      pixels);
        //            await encoder.FlushAsync();
        //        }


        //        FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(sFile);
        //        return status;
        //    }
        //    return FileUpdateStatus.Failed;
        //}
        public async Task<StackPanel> HtmlPraseDeep(string inputString)
        {
            StackPanel mainContianer = new StackPanel();//主容器
            try
            {
                MatchCollection codeMatches = Regex.Matches(inputString, @"<pre>([\s\S]+?)</pre>");
                if (codeMatches.Count != 0)
                {
                    inputString = Regex.Replace(inputString, @"<pre>([\s\S]+?)</pre>", "<code>");
                    List<string> codeList = new List<string>();
                    string oneCode = null;
                    for (int i = 0; i < codeMatches.Count; i++)
                    {
                        oneCode = Regex.Replace(codeMatches[i].Groups[1].ToString(), "<[^>]+?>", "");
                        oneCode = oneCode.Replace("\n", "<br />");
                        codeList.Add(oneCode);
                    }

                    //然后将原来的代码段插入
                    MatchCollection codeAdressMatch = Regex.Matches(inputString, "<code>");
                    for (int i = 0; i < codeList.Count; i++)
                    {
                        inputString = inputString.Insert(codeAdressMatch[i].Index, codeList[i]);
                    }
                }

                //将换行和制表符给去掉,并将应解析的换行显示出来
                inputString = inputString.Replace("\n", "");
                inputString = inputString.Replace("\t", "");
                inputString = Regex.Replace(inputString, @"<p[^>]+?>", "\n");
                inputString = inputString.Replace("</p>", "\n");
                inputString = Regex.Replace(inputString, @"<br([\s\S]+?)/>", "\n");
                //匹配特殊元素
                MatchCollection imgMatches = Regex.Matches(inputString, @"<img[\s\S]+?>");
                MatchCollection linkMatches = Regex.Matches(inputString, @"<a[\s\S]+?</a>");
                MatchCollection videoMatches = Regex.Matches(inputString, @"<iframe[\s\S]+?>");

                List<KeyValuePair<bool, string>> imgList = new List<KeyValuePair<bool, string>>();
                List<KeyValuePair<string, string>> linkList = new List<KeyValuePair<string, string>>();
                List<string> videoList = new List<string>();

                //如果找到了图像则做标记
                if (imgMatches.Count != 0)
                {
                    inputString = Regex.Replace(inputString, @"<img[\s\S]+?>", "(img)");
                    bool large = true;
                    string oneImage = null;
                    for (int i = 0; i < imgMatches.Count; i++)
                    {
                        oneImage = null;
                        large = true;
                        oneImage = Regex.Match(imgMatches[i].Value, @"src=""([^""]+?)""").Groups[1].Value;
                        if (string.IsNullOrEmpty(Regex.Match(imgMatches[i].Value, @"height=""([^""]+?)""").Groups[1].Value))
                            large = false;
                        imgList.Add(new KeyValuePair<bool, string>(large, oneImage));
                    }
                }
                //如果找到了超链接则做标记
                if (linkMatches.Count != 0)
                {
                    inputString = Regex.Replace(inputString, @"<a[\s\S]+?</a>", "(link)");
                    string oneLink = null;
                    string key = null;
                    for (int i = 0; i < linkMatches.Count; i++)
                    {
                        oneLink = null;
                        key = null;
                        oneLink = Regex.Match(linkMatches[i].Value, @"href=""([^""]+?)""").Groups[1].Value;
                        key = Regex.Match(linkMatches[i].Value, @">([^<]+?)</a>").Groups[1].Value;
                        //if (string.IsNullOrEmpty(oneLink) && string.IsNullOrEmpty(text))
                        linkList.Add(new KeyValuePair<string, string>(key, oneLink));
                    }
                }
                //如果找到了视频则做标记
                if (videoMatches.Count != 0)
                {
                    inputString = Regex.Replace(inputString, @"<iframe[\s\S]+?>", "(video)");
                    string oneVideo = null;
                    for (int i = 0; i < videoMatches.Count; i++)
                    {
                        oneVideo = null;
                        oneVideo = Regex.Match(videoMatches[i].Value, @"src=""([^""]+?)""").Groups[1].Value;
                        videoList.Add(oneVideo);
                    }
                }


                //将所有其他的HTML标签给去掉
                inputString = Regex.Replace(inputString, "<[^>]+?>", "");
                //在此去除前导空白符和后导空白符
                inputString = inputString.Trim();
                //将HTML标签还原
                inputString = Regex.Replace(inputString, @"\(img\)", "<img>");
                inputString = Regex.Replace(inputString, @"\(link\)", "<link>");
                inputString = Regex.Replace(inputString, @"\(video\)", "<video>");
                //将去掉的特殊元素复原
                MatchCollection objectMatches = Regex.Matches(inputString, @"<([^>]+?)>");

                if (objectMatches.Count != 0)//如果有特殊元素,则解析特殊元素
                {
                    int imgNumber = 0, linkNumber = 0, videoNumber = 0;
                    string item = null;
                    string lastItem = null;
                    for (int i = 0; i < objectMatches.Count; i++)
                    {
                        item = objectMatches[i].Groups[1].Value;

                        string text = null;

                        text = inputString.Remove(objectMatches[i].Index);
                        if (i != 0)
                        {
                            lastItem = objectMatches[i - 1].Groups[1].Value;
                            switch (lastItem)
                            {
                                case "img":
                                    if (text.Length == objectMatches[i - 1].Index + 6)
                                        text = "";
                                    else
                                        text = text.Substring(objectMatches[i - 1].Index + 5);
                                    break;
                                case "link":
                                    if (text.Length == objectMatches[i - 1].Index + 7)
                                        text = "";
                                    else
                                        text = text.Substring(objectMatches[i - 1].Index + 6);
                                    break;
                                case "video":
                                    if (text.Length == objectMatches[i - 1].Index + 8)
                                        text = "";
                                    else
                                        text = text.Substring(objectMatches[i - 1].Index + 7);
                                    break;
                            }
                        }
                        if (!string.IsNullOrEmpty(text))
                        {

                            if (text.Length != 0)
                            {
                                text = text.Replace("&lt;", "<");
                                text = text.Replace("&gt;", ">");
                                text = text.Replace("&amp;", "&");
                                TextBlock textBlock = new TextBlock();
                                textBlock.Text = text;
                                textBlock.TextWrapping = Windows.UI.Xaml.TextWrapping.Wrap;
                                textBlock.Foreground = new SolidColorBrush(Colors.Black);
                                textBlock.FontSize = 20;
                                mainContianer.Children.Add(textBlock);
                            }

                        }
                        //解析特殊元素
                        switch (item)
                        {
                            case "img":
                                MemoryStream imageStream = null;
                                BitmapImage bm = null;
                                Image img = new Image();
                                //如果碰到相同的图像则只显示一张图
                                if ((imgNumber != 0) && (imgList[imgNumber].Value == imgList[imgNumber - 1].Value) && (string.IsNullOrEmpty(text)))
                                {
                                    imgNumber++;
                                    break;
                                }
                                img.Source = new BitmapImage(new Uri(imgList[imgNumber].Value));

                                //List<string> photoInfo = new List<string>();
                                ////判断是否为大图片
                                //string x = StorageService.Current.ReadSettings(imgList[imgNumber].Value);
                                //if (x == "0")//不是大图片,获取缓存文件
                                //{
                                //    photoInfo = await CacheService.Current.GetImage(imgList[imgNumber].Value);
                                //}
                                //else
                                //{
                                //    photoInfo.Add("NotFound");
                                //    photoInfo.Add("3000");
                                //    photoInfo.Add("3000");
                                //}
                                //判断是否存在缓存的图片文件
                                //if (photoInfo[0] == "NotFound")
                                //{
                                //    if (photoInfo.Count == 1)
                                //    {
                                //        //不存在缓存文件,通过网络下载
                                //        imageStream = await HttpService.Current.DownloadImage(imgList[imgNumber].Value);

                                //        img.Height = HttpService.Current.height;
                                //        img.Width = HttpService.Current.width;

                                //        //MemoryStream copyStream = new MemoryStream();
                                //        //byte[] buffer = new byte[imageStream.Length];
                                //        //int read = 0;
                                //        //do
                                //        //{
                                //        //    // 如果read等于0表示Stream的数据已经读取完毕
                                //        //    read = await imageStream.ReadAsync(buffer, 0, buffer.Length);
                                //        //} while (read != 0);
                                //        //copyStream.Write(buffer, 0, buffer.Length);
                                //        //copyStream.Seek(0, SeekOrigin.Begin);
                                //        if (HttpService.Current.height != 23)
                                //        {
                                //            if (HttpService.Current.height < 2000 && HttpService.Current.width < 2000)
                                //            {
                                //                await CacheService.Current.SaveImage(imgList[imgNumber].Value, imageStream);
                                //            }
                                //            else//如果图片太大,则只加载图片的网址
                                //            {
                                //                HyperlinkButton imageLinkButton = new HyperlinkButton();
                                //                imageLinkButton.Foreground = new SolidColorBrush(Color.FromArgb(255, 7, 140, 226));//湖水蓝
                                //                imageLinkButton.FontSize = 20;
                                //                imageLinkButton.FontStyle = Windows.UI.Text.FontStyle.Oblique;
                                //                imageLinkButton.NavigateUri = new Uri(imgList[imgNumber].Value);
                                //                imageLinkButton.Content = "图片太大,请点击此链接查看";
                                //                mainContianer.Children.Add(imageLinkButton);
                                //                StorageService.Current.WriteSettings(imgList[imgNumber].Value, "Large");
                                //                imgNumber++;
                                //                break;
                                //            }
                                //        }
                                //        imageStream.Seek(0, SeekOrigin.Begin);
                                //        bm = new BitmapImage();
                                //        bm.SetSource(imageStream.AsRandomAccessStream());
                                //    }
                                //    else//是大图片,只加载链接
                                //    {
                                //        HyperlinkButton imageLinkButton = new HyperlinkButton();
                                //        imageLinkButton.Foreground = new SolidColorBrush(Color.FromArgb(255, 7, 140, 226));//湖水蓝
                                //        imageLinkButton.FontSize = 20;
                                //        imageLinkButton.FontStyle = Windows.UI.Text.FontStyle.Oblique;
                                //        imageLinkButton.NavigateUri = new Uri(imgList[imgNumber].Value);
                                //        imageLinkButton.Content = "图片太大,请点击此链接查看";
                                //        mainContianer.Children.Add(imageLinkButton);
                                //        imgNumber++;
                                //        //StorageService.Current.WriteSettings(imgList[imgNumber].Value, "Large");
                                //        break;
                                //    }
                                //}
                                //else
                                //{
                                //    bm = new BitmapImage(new Uri(photoInfo[0], UriKind.Absolute));
                                //    img.Height = Convert.ToUInt32(photoInfo[1]);
                                //    img.Width = Convert.ToUInt32(photoInfo[2]);
                                //}

                                //if (imageStream == null && (string.IsNullOrEmpty(photoInfo[0])))//防止程序错误
                                //{
                                //    imgNumber++;
                                //    break;
                                //}

                                ////开始设置Image控件的属性，并将其添加到主容器                                
                                //if (img.Width > 360)
                                //{
                                //    img.Height = img.Height * 360 / img.Width;
                                //    img.Width = 360;
                                //    img.Stretch = Stretch.Uniform;
                                //}
                                //img.Source = bm;
                                img.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                                mainContianer.Children.Add(img);
                                imgNumber++;
                                break;
                            case "link":
                                if (string.IsNullOrEmpty(linkList[linkNumber].Key))//防止程序错误
                                {
                                    linkNumber++;
                                    break;
                                }
                                HyperlinkButton linkButton = new HyperlinkButton();
                                linkButton.Foreground = new SolidColorBrush(Color.FromArgb(255, 7, 140, 226));//湖水蓝
                                linkButton.FontSize = 20;
                                linkButton.FontStyle = Windows.UI.Text.FontStyle.Oblique;
                                linkButton.NavigateUri = new Uri(linkList[linkNumber].Value);
                                linkButton.Content = linkList[linkNumber].Key;
                                mainContianer.Children.Add(linkButton);
                                linkNumber++;
                                break;
                            case "video":
                                if (string.IsNullOrEmpty(videoList[videoNumber]))//防止程序错误
                                {
                                    videoNumber++;
                                    break;
                                }
                                HyperlinkButton linkVideoButton = new HyperlinkButton();
                                linkVideoButton.Foreground = new SolidColorBrush(Color.FromArgb(255, 7, 140, 226));//湖水蓝
                                linkVideoButton.FontSize = 20;
                                linkVideoButton.FontStyle = Windows.UI.Text.FontStyle.Oblique;
                                linkVideoButton.NavigateUri = new Uri(videoList[videoNumber]);
                                linkVideoButton.Content = "视频链接";
                                mainContianer.Children.Add(linkVideoButton);
                                videoNumber++;
                                break;
                            default: break;
                        }
                    }

                    string text2 = null;
                    item = objectMatches[objectMatches.Count - 1].Groups[1].Value;

                    switch (item)
                    {
                        case "img":
                            if (inputString.Length == objectMatches[objectMatches.Count - 1].Index + 5)
                                text2 = "";
                            else
                                text2 = inputString.Substring(objectMatches[objectMatches.Count - 1].Index + 5);
                            break;
                        case "link":
                            if (inputString.Length == objectMatches[objectMatches.Count - 1].Index + 5)
                                text2 = "";
                            else
                                text2 = inputString.Substring(objectMatches[objectMatches.Count - 1].Index + 6);
                            break;
                        case "video":
                            if (inputString.Length == objectMatches[objectMatches.Count - 1].Index + 7)
                                text2 = "";
                            else
                                text2 = inputString.Substring(objectMatches[objectMatches.Count - 1].Index + 7);
                            break;
                    }
                    if (!string.IsNullOrEmpty(text2))
                    {
                        text2 = text2.Replace("&lt;", "<");
                        text2 = text2.Replace("&gt;", ">");
                        text2 = text2.Replace("&amp;", "&");
                        TextBlock textBlockFinal = new TextBlock();
                        textBlockFinal.Text = text2;
                        textBlockFinal.TextWrapping = Windows.UI.Xaml.TextWrapping.Wrap;
                        textBlockFinal.Foreground = new SolidColorBrush(Colors.Black);
                        textBlockFinal.FontSize = 20;
                        mainContianer.Children.Add(textBlockFinal);
                    }
                }
                else//未找到特殊元素,直接解析文本元素
                {
                    inputString = inputString.Replace("&lt;", "<");
                    inputString = inputString.Replace("&gt;", ">");
                    inputString = inputString.Replace("&amp;", "&");
                    TextBlock textBlock = new TextBlock();
                    //textBlock.Style = res
                    textBlock.Text = inputString;
                    textBlock.TextWrapping = Windows.UI.Xaml.TextWrapping.Wrap;
                    textBlock.Foreground = new SolidColorBrush(Colors.Black);
                    textBlock.FontSize = 20;
                    mainContianer.Children.Add(textBlock);
                }
            }
            catch (Exception ex)
            {
                //message = ex.Message.ToString();
            }
            //if (message != null)
            //{
            //    Msg("网络连接异常，可能是您的网络信号太差，请检查您的网络。\n" + "错误信息" + message);
            //    message = null;
            //}
            return mainContianer;
        }
        public static async Task<FileUpdateStatus> SaveTojpegImage(WriteableBitmap bitmap, PickerLocationId location, string fileName)
        {
            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = location
            };
            savePicker.FileTypeChoices.Add("jpg Image", new[] { ".jpg" });
            savePicker.SuggestedFileName = fileName;
            StorageFile sFile = await savePicker.PickSaveFileAsync();
            if (sFile != null)
            {
                CachedFileManager.DeferUpdates(sFile);


                using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fileStream);
                    Stream pixelStream = bitmap.PixelBuffer.AsStream();
                    byte[] pixels = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);
                    try
                    {
                        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                             (uint)bitmap.PixelWidth,
                             (uint)bitmap.PixelHeight,
                             96.0,
                             96.0,
                             pixels);
                        await encoder.FlushAsync();
                    }
                    catch(Exception ex)
                    {

                    }
                   
                }


                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(sFile);
                return status;
            }
            return FileUpdateStatus.Failed;
        }
        public static async Task<FileUpdateStatus> SaveToPngImage(WriteableBitmap bitmap, PickerLocationId location, string fileName)
        {
            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = location
            };
            savePicker.FileTypeChoices.Add("Png Image", new[] { ".png" });
            savePicker.SuggestedFileName = fileName;
            StorageFile sFile = await savePicker.PickSaveFileAsync();
            if (sFile != null)
            {
                CachedFileManager.DeferUpdates(sFile);


                using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
                    Stream pixelStream = bitmap.PixelBuffer.AsStream();
                    byte[] pixels = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                              (uint)bitmap.PixelWidth,
                              (uint)bitmap.PixelHeight,
                              96.0,
                              96.0,
                              pixels);
                    await encoder.FlushAsync();
                }


                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(sFile);
                return status;
            }
            return FileUpdateStatus.Failed;
        }
        public static List<string> getallowedsites() {
            List<string> filestr = new List<string>();
            filestr.Add("http://*.google.com");
            filestr.Add("http://*.facebook.com");
            filestr.Add("http://*.youtube.com");
            filestr.Add("http://*.baidu.com");
            filestr.Add("http://*.yahoo.com");
            filestr.Add("http://*.amazon.com");
            filestr.Add("http://*.wikipedia.org");
            filestr.Add("http://*.qq.com");
            filestr.Add("http://*.twitter.com");
            filestr.Add("http://*.google.co.in");
            filestr.Add("http://*.taobao.com");
            filestr.Add("http://*.live.com");
            filestr.Add("http://*.sina.com.cn");
            filestr.Add("http://*.linkedin.com");
            filestr.Add("http://*.yahoo.co.jp");
            filestr.Add("http://*.weibo.com");
            filestr.Add("http://*.ebay.com");
            filestr.Add("http://*.google.co.jp");
            filestr.Add("http://*.yandex.ru");
            filestr.Add("http://*.hao123.com");
            filestr.Add("http://*.vk.com");
            filestr.Add("http://*.bing.com");
            filestr.Add("http://*.google.de");
            filestr.Add("http://*.t.co");
            filestr.Add("http://*.msn.com");
            filestr.Add("http://*.instagram.com");
            filestr.Add("http://*.aliexpress.com");
            filestr.Add("http://*.amazon.co.jp");
            filestr.Add("http://*.google.co.uk");
            filestr.Add("http://*.apple.com");
            filestr.Add("http://*.blogspot.com");
            filestr.Add("http://*.ask.com");
            filestr.Add("http://*.pinterest.com");
            filestr.Add("http://*.wordpress.com");
            filestr.Add("http://*.google.fr");
            filestr.Add("http://*.tmall.com");
            filestr.Add("http://*.google.com.br");
            filestr.Add("http://*.reddit.com");
            filestr.Add("http://*.mail.ru");
            filestr.Add("http://*.onclickads.net");   
            filestr.Add("http://*.imgur.com");
            filestr.Add("http://*.microsoft.com");
            filestr.Add("http://*.qq.com/");
            filestr.Add("http://*.taobao.com/");
            filestr.Add("http://*.163.com/");
            filestr.Add("");
            filestr.Add("");

            filestr.Add("");

            filestr.Add("");
            filestr.Add("");

            filestr.Add("");

            filestr.Add("");
            filestr.Add("");
            filestr.Add("");
            filestr.Add("");
            filestr.Add("");

            filestr.Add("");
            filestr.Add("");
            filestr.Add("");
            filestr.Add("");
            filestr.Add("");

            filestr.Add("");

            filestr.Add("");
            filestr.Add("");
            filestr.Add("");
            filestr.Add("");
            filestr.Add("");

            filestr.Add("");
            filestr.Add("");
            filestr.Add("");
            filestr.Add("");

            filestr.Add("");

            filestr.Add("");

            filestr.Add("");
            filestr.Add("");
            filestr.Add("");
            filestr.Add("");
            filestr.Add("");

            filestr.Add("");
            filestr.Add("");
            filestr.Add("");
            filestr.Add("");
            return filestr;
        }
        public static
            async Task changehtmlurl(string url,WebView homewebview)
        {
            if (App.Isdownloadstirngmode)
            {
                string oldsrcreplacestr = "src=\"/";
                string newsrcreplacestr = "src=\"http://" + App.Currenturl.Host + "/";
                string oldhrefreplacestr = "href=\"/";
                string oldhrefwithemptyreplacestr = "href=\"/ ";
                string newhrefreplacestr = "href=\"http://" + App.Currenturl.Host + "/";
                App.Htmlstringcontent = await HtmlUsedFunction.gethtmlstring(url);
                App.Htmlstringcontent = App.Htmlstringcontent.Replace(oldsrcreplacestr, newsrcreplacestr).Replace(oldhrefreplacestr, newhrefreplacestr).Replace(oldhrefwithemptyreplacestr, newhrefreplacestr);
                Debug.WriteLine("new httpstring");
                Debug.WriteLine(App.Htmlstringcontent);
                if (App.Htmlstringcontent.Length > 500)
                {
                    if (App.Iswithoutpicmode)
                    {
                        App.Htmlstringcontent = App.Htmlstringcontent.Replace("jpg", "1jpg");
                        App.Htmlstringcontent = App.Htmlstringcontent.Replace("png", "1png");
                        string ScriptTagString = "<script lang=\"en-us\" type=\"text/javascript\">";
                        string strr = "function SayHelloWorld(me) {    var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {   imgboxes[i].onclick = function(){  window.external.notify(this.src);  }; } }";
                        int IndexOfScriptTag = App.Htmlstringcontent.IndexOf("</head>");
                        string InsertionScriptString = strr;
                        //  int LengthOfScriptTag = ScrstriptTagString.Length;
                        //  string InsertionScriptString = "function SayHelloWorld(wo) { window.external.notify(\"Hello World!\");}";
                        string endscript = "</script>";
                        // reuslt = reuslt.TrimEnd();
                        App.Htmlstringcontent = App.Htmlstringcontent.Insert(IndexOfScriptTag, ScriptTagString + InsertionScriptString + endscript);
                        Debug.WriteLine(ScriptTagString + InsertionScriptString + endscript);
                        // reuslt = reuslt.Insert(IndexOfScriptTag + LengthOfScriptTag + 1, InsertionScriptString);
                        // MyWebview.NavigateToString(reuslt);
                        Debug.WriteLine(App.Htmlstringcontent);
                        homewebview.NavigateToString(App.Htmlstringcontent);
                    }
                    else
                    {
                        string ScriptTagString = "<script lang=\"en-us\" type=\"text/javascript\">";
                        string strr = "function SayHelloWorld(me) {    var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {   imgboxes[i].onclick = function(){  window.external.notify(this.src);  }; } }";
                        int IndexOfScriptTag = App.Htmlstringcontent.IndexOf("</head>");
                        string InsertionScriptString = strr;
                        //  int LengthOfScriptTag = ScrstriptTagString.Length;
                        //  string InsertionScriptString = "function SayHelloWorld(wo) { window.external.notify(\"Hello World!\");}";
                        string endscript = "</script>";
                        // reuslt = reuslt.TrimEnd();
                        App.Htmlstringcontent = App.Htmlstringcontent.Insert(IndexOfScriptTag, ScriptTagString + InsertionScriptString + endscript);
                        Debug.WriteLine(ScriptTagString + InsertionScriptString + endscript);
                        // reuslt = reuslt.Insert(IndexOfScriptTag + LengthOfScriptTag + 1, InsertionScriptString);
                        // MyWebview.NavigateToString(reuslt);
                        Debug.WriteLine(App.Htmlstringcontent);
                        homewebview.NavigateToString(App.Htmlstringcontent);
                    }
                }
                else
                {
                    homewebview.Navigate(App.Currenturl);
                }

            }
            else
            {

                homewebview.Navigate(App.Currenturl);
            }
        }

        public static string getnamebyurl(string url)
        {
            string result = string.Empty;
            if(url.Contains('/'))
            {
                int i = url.LastIndexOf('/');
           string resultlist=      url.Substring(i+1);
                return resultlist;
            }
            return result;
        }
        
    }
}
